package xyccontroller

import (
	"Cgo/backend/models"
	"Cgo/common"
	"strconv"

	"github.com/gin-gonic/gin"
)

func XycAddressController(r *gin.RouterGroup) {
	r.POST("/add", common.HandlerFunc(AddAddress))
	r.DELETE("/delete", common.HandlerFunc(DeleteAddress))
	r.PUT("/update", common.HandlerFunc(UpdateAddress))
	r.GET("/find", common.HandlerFunc(FindAddress))
}

// 添加地址
// @Summary 添加地址
// @Tags xyc_shop后台接口
// @Accept json
// @Produce json
// @Param address body models.XycAddress true "地址信息"
// @Success 200 {object} common.RT[string]
// @Router /backend/xyc/address/add [post]
func AddAddress(c *gin.Context) common.Result {
	var address models.XycAddress
	if err := c.ShouldBindJSON(&address); err != nil {
		return common.R.Fail(err.Error())
	}
	if err := AddressDao.AddAddressDao(address); err != nil {
		return common.R.Fail(err.Error())
	}
	return common.R.Success("添加地址成功")
}

// 删除地址
// @Summary 删除地址
// @description 根据id删除地址
// @Tags xyc_shop后台接口
// @Accept json
// @Produce json
// @Param id query int true "地址id"
// @Success 200 {object} common.RT[string]
// @Router /backend/xyc/address/delete [delete]
func DeleteAddress(c *gin.Context) common.Result {
	idStr := c.Query("id")
	id, _ := strconv.Atoi(idStr)
	address := models.XycAddress{Id: id}
	if err := AddressDao.DeleteAddressDao(address); err != nil {
		return common.R.Fail(err.Error())
	}
	return common.R.Success("删除地址成功")
}

// 更新地址
// @Summary 更新地址
// @Tags xyc_shop后台接口
// @Accept json
// @Produce json
// @Param address body models.XycAddress true "地址信息"
// @Success 200 {object} common.RT[string]
// @Router /backend/xyc/address/update [put]
func UpdateAddress(c *gin.Context) common.Result {
	var address models.XycAddress
	if err := c.ShouldBindJSON(&address); err != nil {
		return common.R.Fail(err.Error())
	}
	if err := AddressDao.UpdateAddressDao(address); err != nil {
		return common.R.Fail(err.Error())
	}
	return common.R.Success("更新地址成功")
}

// 查找地址
// @Summary 查找地址
// @description 根据id查找地址
// @Tags xyc_shop后台接口
// @Accept json
// @Produce json
// @Param id query int false "地址id"
// @Success 200 {object} common.RT[[]models.XycAddress]
// @Router /backend/xyc/address/find [get]
func FindAddress(c *gin.Context) common.Result {
	idStr := c.Query("id")
	var id int
	if idStr != "" {
		id, _ = strconv.Atoi(idStr)
	}
	address := models.XycAddress{Id: id}
	addresses, err := AddressDao.FindAddressByIdDao(address)
	if err != nil {
		return common.R.Fail(err.Error())
	}
	return common.R.Success(addresses)
}
